package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.dto.CreateCarriageRequest;
import server.demo.dto.CarriageDTO;
import server.demo.service.CarriageService;

import jakarta.validation.Valid;
import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/carriages")
@CrossOrigin(origins = "*")
public class CarriageController {
    
    @Autowired
    private CarriageService carriageService;
    
    @GetMapping
    public ApiResponse<List<CarriageDTO>> getAllCarriages() {
        try {
            List<CarriageDTO> carriages = carriageService.getAllCarriages();
            return ApiResponse.success(carriages);
        } catch (Exception e) {
            return ApiResponse.error("获取车厢列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/train/{trainId}")
    public ApiResponse<List<CarriageDTO>> getCarriagesByTrainId(@PathVariable Long trainId) {
        try {
            List<CarriageDTO> carriages = carriageService.getCarriagesByTrainId(trainId);
            return ApiResponse.success(carriages);
        } catch (Exception e) {
            return ApiResponse.error("获取车厢列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public ApiResponse<CarriageDTO> getCarriageById(@PathVariable Long id) {
        try {
            Optional<CarriageDTO> carriage = carriageService.getCarriageById(id);
            if (carriage.isPresent()) {
                return ApiResponse.success(carriage.get());
            } else {
                return ApiResponse.error("车厢不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取车厢信息失败: " + e.getMessage());
        }
    }
    
    @PostMapping
    public ApiResponse<CarriageDTO> createCarriage(@Valid @RequestBody CreateCarriageRequest request) {
        try {
            CarriageDTO carriage = carriageService.createCarriage(request);
            return ApiResponse.success("车厢创建成功", carriage);
        } catch (Exception e) {
            return ApiResponse.error("创建车厢失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<CarriageDTO> updateCarriage(@PathVariable Long id, @Valid @RequestBody CreateCarriageRequest request) {
        try {
            CarriageDTO carriage = carriageService.updateCarriage(id, request);
            return ApiResponse.success("车厢更新成功", carriage);
        } catch (Exception e) {
            return ApiResponse.error("更新车厢失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteCarriage(@PathVariable Long id) {
        try {
            carriageService.deleteCarriage(id);
            return ApiResponse.success("车厢删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除车厢失败: " + e.getMessage());
        }
    }
}